<template>
  <div id="app" class="flex">
    <div class="n-box flex-lefr">
      <div class="flex homelog-box">
        <img class="homeLog" :src="'./img/ptlog.png'"/>
        <div class="homlog-r flex-right"></div>
      </div>

      <div class="n-ul">
        <div class="n-li" v-for="(item, index) in navigation" :key="index">
          <div class="n-li-box" :class="currentPath === item.url ? 'n-opt' : ''">
            <img :src="currentPath == item.url ? item.imgOpt : item.img"/>
            <div>
              <router-link :to="item.url" @click="setNavigation(item.id)">{{ item.text }}</router-link>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="headline-box flex-right flex">
      <div class="headline-text">{{ userData.username == 'root' ? '短波频率规划终端' : userData.platform.name }}</div>
      <div class="headline-menu flex-right flex ">
        <img :src="'./img/userlog.png'" class="m-img1">
        <div class="">管理员 {{ setPhone(userData.phone) }}</div>
        <img :src="'./img/setpwd.png'" class="m-img2">
        <div class="cursor" @click="setPassword">修改密码</div>
        <img :src="'./img/kz.png'" class="m-img3 cursor" @click="toggleFullscreen"/>
        <div class="cursor" style="margin-right:30px;" @click="logout">注销</div>

      </div>
    </div>


    <el-dialog v-model="visible" :title="'修改密码'" width="558">
      <el-form :model="form" label-width="120px">
        <el-form-item label="新密码">
          <el-input v-model="form.newPassword" placeholder="新密码" type="password"/>
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="form.affirmPassword" placeholder="确认密码" type="password"/>
        </el-form-item>
        <el-form-item label="短信验证码">
          <div class="flex">
            <el-input v-model="form.code" placeholder="短信验证码" type="text"/>
            <div class="input-verify-phone" @click="startCountdown()" :class="{ 'counting': counting }">{{ buttonText }}
            </div>
          </div>

        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="postPassword">
            确定
          </el-button>
        </span>
      </template>

    </el-dialog>


  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  defineEmits,
  watchEffect,
  onBeforeMount,
  onBeforeUnmount,
  getCurrentInstance,
} from "vue";
import {useRoute} from 'vue-router';
import {ElMessage, ElMessageBox} from 'element-plus'
import config from "@/config";

const {
  proxy
} = getCurrentInstance();


// const props = defineProps(['emit']);
const emits = defineEmits();


const route = useRoute();
const currentPath = ref('');
const pitch = ref(null);
const opt = ref(1);//导航栏选中
const optList = ref(1);//导航栏子集选中
const navigation = ref([
  {id: 1, text: "用户基础信息", img: './img/pt1.png', imgOpt: './img/pto1.png', url: '/userinfo'},
  {id: 2, text: "系统角色管理", img: './img/pt2.png', imgOpt: './img/pto2.png', url: '/role'},
  {id: 3, text: "系统平台管理", img: './img/pt3.png', imgOpt: './img/pto3.png', url: '/platform'},
  {id: 4, text: "菜单权限管理", img: './img/pt4.png', imgOpt: './img/pto4.png', url: '/menu'},
]);

//根据用户平台id查询平台信息
// 存储对象
const userData = ref();
//修改密码
const visible = ref(false);
const setUser = ref();
const form = ref({
  newPassword: null,
  affirmPassword: null,
  code: null,
});

const counting = ref(false);
const countdown = ref(59);
const buttonText = ref('获取验证码');

function setPitch(index) {
  pitch.value = index;
}


function setPassword() {//修改密码
  form.value = {
    newPassword: null,
    affirmPassword: null,
    code: null,
  }
  visible.value = true;
}

function postPassword() {
  console.log(userData.value);
  if (form.value.newPassword == null || form.value.affirmPassword == null
      || form.value.affirmPassword == '' || form.value.newPassword == ''
  ) {
    ElMessage({
      message: '密码不能为空!',
      type: 'error',
    })
    return
  }

  if (form.value.affirmPassword != form.value.newPassword) {
    ElMessage({
      message: '两次密码不一致!',
      type: 'error',
    })
    return
  }
  const data = {
    password: form.value.affirmPassword,
    code: form.value.code,
  }
  proxy.$Request.post(proxy.$urlApi.login.resetPwd, data)
      .then((res) => {
        if (res.data.code != 200) {
          ElMessage({
            message: res.data.msg,
            type: 'error',
          })
        } else {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          visible.value = false;
        }
      }).catch(error => {
  });
}


const startCountdown = () => {
  if (countdown.value === 59) {

    if (!getCode()) {
      return
    }
  }
  if (!counting.value) {
    counting.value = true;
    buttonText.value = '60s重新获取'
    const timer = setInterval(() => {
      countdown.value -= 1;
      buttonText.value = countdown.value + 's重新获取'
      if (countdown.value === 0) {
        buttonText.value = '获取验证码'
        clearInterval(timer);
        counting.value = false;
        countdown.value = 59;
      }
    }, 1000);
  } else {
  }
};


const toggleFullscreen = () => {
  const element = document.documentElement;
  if (!document.fullscreenElement) {
    element.requestFullscreen().catch((err) => {
      console.error(`全屏失败：${err.message}`);
    });
  } else {
    document.exitFullscreen();
  }
};

async function getCode() {
  const data = {
    phone: userData.value.phone
  }
  proxy.$Request.post(proxy.$urlApi.login.code, data)
      .then((res) => {
        if (res.data.code != 200) {

          ElMessage({
            message: res.data.msg,
            type: 'error',
          })
          return false;
        } else {
          ElMessage({
            message: '已发送',
            type: 'success',
          })
          return true;
        }
      }).catch(error => {
  });
}

function logout() {
  ElMessageBox.confirm(
      '是否注销登录?',
      '注销',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }
  )
      .then(() => {
        let tokenData = localStorage.getItem('TOKENDATA');
        if (tokenData) {
          tokenData = JSON.parse(tokenData)
          proxy.$Request.post(proxy.$urlApi.login.logout, tokenData)
              .then((res) => {
                if (res.data.code != 200) {
                  ElMessage({
                    message: res.data.msg,
                    type: 'error',
                  })
                } else {
                  localStorage.clear()
                  const local = location.origin
                  location.replace(config.baseUrl + "/security/logout?redirect_uri=" + local)
                }
              }).catch(error => {
          });
        }
      })
      .catch(() => {
      })
}

function setNavigation(id) {
  opt.value = id;
  optList.value = 1;
}

function setPhone(phone) {
  // 使用正则表达式在手机号中添加空格分隔符
  return phone.replace(/(\d{4})(\d{4})(\d{4})/, '$1 $2 $3');
}

function setFull() {
  // route.meta.hideNavigationBar = true;
  emits('setFull', true);
}


onBeforeMount(() => {
  //localStorage.setItem('userData', JSON.stringify(userData));
  // 读取对象
  const savedData = localStorage.getItem('USERINFO');
  // console.log(savedData);
  // 如果你需要将 JSON 字符串转换回对象，可以使用 JSON.parse
  userData.value = JSON.parse(savedData);
  // console.log(userData.value);

  // 初始赋值
  currentPath.value = route.path;
  // 监听路由变化
  // 监听路由变化

});


watchEffect(() => {
  currentPath.value = route.path;
});


// 处理按下 Esc 键的函数
const handleKeyPress = (event) => {
  if (event.key === 'Escape') {
    // 执行你的事件处理逻辑
    emits('setFull', false);
  }
};

onMounted(() => {
  // 在组件挂载时添加全局键盘事件监听器
  window.addEventListener('keydown', handleKeyPress);
});

onBeforeUnmount(() => {
  // 在组件销毁前移除全局键盘事件监听器，以防止内存泄漏
  window.removeEventListener('keydown', handleKeyPress);
});

</script>

<style lang="scss">
.n-box {
  width: 234px;
  height: 100vh;
  // background: linear-gradient(to bottom, #2C334C, #1D2435);
  background-size: cover;
  overflow: hidden;
  display: inline-block;
  background: white;
  font-size: 16px;
}

.homeLog {
  width: 206px;
  height: 68px;
}

.homlog-r {
  width: 6px;
  height: 37px;
  // background: #D8D8D8;
  border-left: solid 6px #D8D8D8;

}

.homelog-box {
  align-items: center;
  /* 垂直居中对齐图像和输入框 */
  // width: 206px;
}

.n-ul {
  height: calc(100vh - 234px);
  // background: url(../../../public/img/n_ul.png) center bottom no-repeat;
  overflow: hidden;
  color: #72767C;
  margin-left: 30px;
  margin-top: 40px;
}

.n-li {
  width: 198px;
  height: 40px;

}

.n-li-box {
  display: flex;
  align-items: center;
  padding: 10px 10px;
  border-radius: 5px;
  margin: 5px 0;
  cursor: pointer;
}

.n-li-box a {
  color: #72767C;
  font-size: 16px;
  text-decoration: none;

}

.n-li-box img {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}


.n-opt {
  background: #F3F5F8;
  color: #2CA6E0;
}

.n-opt a {
  background: #F3F5F8;
  color: #2CA6E0;
}


.headline-box {
  min-width: calc(100% - 234px);
  height: 70px;
  background: white;
  font-size: 16px;

}

.headline-text {
  font-size: 32px;
  font-weight: 700;
  width: 400px;
  height: 44px;
  margin: 13px;
  // line-height: 45px;
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 超出部分隐藏 */

}

.headline-menu {
  // height: 44px;
  // // cursor: pointer; 
  // margin-top: 13px;
  // margin-bottom: 14px;
  line-height: 70px;
  align-items: center;
  color: #9E9E9E;
  font-weight: 700;
  white-space: nowrap;
  /* 防止文本换行 */
  overflow: hidden;
  /* 超出部分隐藏 */

}

.m-img1,
.m-img2,
.m-img3 {
  vertical-align: middle;
}

.m-img1 {
  height: 40px;
  width: 40px;
  margin-right: 20px;
}

.m-img2 {
  height: 24px;
  width: 24px;
  margin-left: 20px;
  margin-right: 20px;
}

.m-img3 {
  height: 20px;
  width: 20px;
  margin-left: 20px;
  margin-right: 20px;
}

// 短信验证码
.input-verify-phone {
  margin-left: 30px;
  width: 200px;
  text-align: center;
  color: #2CA6E0;
  border: solid 1px #2CA6E0;
  padding: 4px 0;
  margin-right: 1px;
  border-radius: 20px;
  font-size: 16px;
  cursor: pointer;
  /* 将光标设置为手指 */
}

.counting {
  cursor: not-allowed;
  /* 添加样式以指示按钮处于不可点击状态 */
}
</style>